
import os
import logging
import re
from datetime import datetime, timedelta
from cStringIO import StringIO

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import mail

import jinja2
from jinja2 import Environment, FileSystemLoader

# webpy
from web import utils
from web import urlquote

from appengine_utilities.sessions import Session

DEV = False
if 'DEV' in os.listdir('.'):
    DEV = True

ENV = Environment(loader=FileSystemLoader('templates/'), autoescape=True,
                  auto_reload=DEV, line_statement_prefix='#')

def cond(c, str, other=''):
  if c:
    return str
  return other
ENV.globals['cond'] = cond

ENV.globals['urlquote'] = urlquote


def number_format(num, places=0):
   """Format a number with grouped thousands and given decimal places"""

   # in utils, commify(n) adds commas to an int

   places = max(0,places)
   tmp = "%.*f" % (places, num)
   point = tmp.find(".")
   integer = (point == -1) and tmp or tmp[:point]
   decimal = (point != -1) and tmp[point:] or ""

   count = 0
   formatted = []
   for i in range(len(integer), 0, -1):
       count += 1
       formatted.append(integer[i - 1])
       if count % 3 == 0 and i - 1:
           formatted.append(",")

   integer = "".join(formatted[::-1])
   return integer+decimal
ENV.filters['number_format'] = number_format


def simple_name(name, sep='-'):
    """
    Create nice names to put in urls like stackoverflow.com but with endings
    cut off at the word level rather than the character level.
    """
    name = re.sub('[ /\.\-]+', '-', re.sub(r'[^\w\-\./ ]+', '', name)).lower()
    if len(name) > 80:
        name = name[:81]
        name = name[:name.rfind('-')]
    return name.strip('-')
ENV.filters['simple_name'] = simple_name


def valid_email(email):
    if len(email) <= 5: # a@b.ca
        return 0
    if not re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,6}|[0-9]{1,6})(\\]?)$", email):
        return 0
    return 1


class RenderHandler(webapp.RequestHandler):
  def render(self, template, args={}, ext='.html'):
      content = ENV.get_template(template + ext).render(args)
      self.response.out.write(content)
 
  def write(self, str):
      self.response.out.write(str)
      #self.response.out.write('<br />')

  def req_get(self, k):
      return self.request.get(k)


def get_session():
    secure, httponly = False, True
    if DEV:
        secure = False
    session = Session(cookie_name='kawarthagrowers.appspot', secure=secure, httponly=httponly)
    return session


import re
import cgi

re_string = re.compile(r'(?P<htmlchars>[<&>])|(?P<space>^[ \t]+)|(?P<lineend>\r\n|\r|\n)|(?P<protocal>(^|\s)((http|ftp)://.*?))(\s|$)', re.S|re.M|re.I)
def plaintext2html(text, tabstop=4, link_style=''):
    #text = web.websafe(text) # unnecessary?
    # does this do a good enough job protecting?
    #    i think so but i'm no expert..
    def do_sub(m):
        c = m.groupdict()
        if c['htmlchars']:
            return cgi.escape(c['htmlchars'])
        if c['lineend']:
            return '<br />'
        elif c['space']:
            t = m.group().replace('\t', '&nbsp;'*tabstop)
            t = t.replace(' ', '&nbsp;')
            return t
        elif c['space'] == '\t':
            return ' '*tabstop
        else:
            url = m.group('protocal')
            if url.startswith(' '):
                prefix = ' '
                url = url[1:]
            else:
                prefix = ''
            last = m.groups()[-1]
            if last in ['\n', '\r', '\r\n']:
                last = '<br />'
            # handle too long urls that firefox 2 won't wrap
            url2 = url
            display_url = ""
            while len(url2) > 78:
                display_url += url2[:78] + " "
                url2 = url2[78:]
            display_url += url2
            return '%s<a href="%s" style="%s">%s</a>%s' % (prefix, url, link_style, display_url, last)
    return re.sub(re_string, do_sub, text)

ENV.filters['plaintext2html'] = plaintext2html

# seconds | minutes | hours & minutes | days | weeks 
def fminute(seconds, postfix=' min'):
    #if seconds < 120:
    #    ret = '1 mine'
    #else:
    ret = ''
    if seconds > 59:
        ret = '%d%s' % (seconds / 60, postfix)
    return ret
def as_time_ago(dtime):
    td = datetime.utcnow() - dtime
    ret = ''
    hour = 60 * 60
    if not td.days:
        if td.seconds < 60:
            if td.seconds == 1:
                ret = '1 s'
            else:
                ret = '%d s' % td.seconds
        elif td.seconds < hour:
            ret = fminute(td.seconds)
        else:
            if td.seconds < hour * 2:
                ret = '1 hr'
            else:
                ret = '%d hrs' % (td.seconds / hour)
                                        # only show min for <= 6 hrs
            if td.seconds % hour != 0 and (td.seconds / hour) < 7:
                ret += ' ' + fminute(td.seconds % hour)
    else: # td.days < 7:
        if td.days == 1:
            ret = '1 day'
        else:
            ret = '%d days' % td.days
    #else:
    #    if td.days == 7:
    #        ret = '1 week'
    #    else:
    #        ret = '%d weeks' % (td.days / 7)

    return ret + ' ago'

ENV.filters['as_time_ago'] = as_time_ago